package com.tianpengtech.front.mobile.login;


import com.jfinal.kit.Ret;
import com.tianpengtech.admin.dictionary.DictionaryDao;
import com.tianpengtech.common.model.dictionary.Dictionary;
import com.tianpengtech.common.model.fair.Fair;
import com.tianpengtech.common.model.moneylog.MoneyLog;
import com.tianpengtech.common.model.task.Task;
import com.tianpengtech.common.model.user.User;
import com.tianpengtech.front.mobile.common.constant.Constant;
import com.tianpengtech.front.mobile.common.util.R;
import com.tianpengtech.front.mobile.common.util.TokenUtil;
import com.tianpengtech.front.mobile.common.util.UserUtil;
import com.tianpengtech.front.web.login.LoginService;
import com.tianpengtech.front.web.passport.PassportService;

import java.util.UUID;


/**
 * Created by ggd on 2017/7/17 0017.
 */
public class MobileLoginService {

    public static final MobileLoginService me = new MobileLoginService();
    private final LoginService loginService = LoginService.me;
    private final PassportService passportService = PassportService.me;
    private final User userDao = new User().dao();
    private DictionaryDao dictionaryDao = new DictionaryDao();
    //用户密码错误次数 缓存key
    public static final String ERRORCOUNT_KEY = "error_count_";

    //用户错误密码次数 缓存名称
    public static final String ERRORCOUNT_CACHENAME = "errorcount";





    /**
     * 登录
     */
    public R login(String mobile, int code, String loginIp,String source) throws Exception {
        try{
            try {
                if(!passportService.authCode(mobile,loginIp,code,true)){
                    return R.fail("验证码不正确");
                }
            }catch (Exception e){
                e.printStackTrace();
                return R.fail("验证码不正确");
            }
            User user = loginService.findByMobile(mobile,User.USER_TYPE_FAIR);
            if (user == null) {
                Ret r=passportService.reg(mobile, Constant.DEFAULT_PASSWORD,User.USER_TYPE_FAIR);
                if (r.isOk()){
                    long id= (long) r.get("id");
                    Fair fair = new Fair();
                    fair.set(Fair.ID,id);
                    fair.save();
                    user=loginService.findByMobile(mobile,User.USER_TYPE_FAIR);
                    user.set(User.CODE,getCode());
                    user.update();
                }else{
                    return R.fail("注册失败");
                }
            }
            if (user.isStatusLockId()) {
                return R.fail("账号已被锁定");
            }
            user.removeSensitiveInfo();  // 移除 password 与 salt 属性值
            String token = TokenUtil.getToken();
            UserUtil.setCurrentUser(user,token,source);
            loginService.createLoginLog(user.getLong(User.ID), loginIp,"mobile");
            user.remove(User.DELETETAG).remove(User.USER_TYPE).remove(User.STATUS).remove(User.CREATE_TIME);
            R r=R.ok("登陆成功");
            r.p("user",user);
            r.p("token",token);
            return r;
        }catch (Exception e){
            throw e;
        }

    }

    /**
     * 退出登录
     * @param token
     * @return
     */
    public R logout(String token){
        UserUtil.removeUser(token);
        return R.ok("退出成功");
    }


    /**
     * 邀请注册
     * @return
     */
    public R inviteReg(String code,String mobile,int authCode,String regIp) throws Exception{
        try{
            try {
                if(!passportService.authCode(mobile,regIp,authCode,true)){
                    return R.fail("验证码不正确");
                }
            }catch (Exception e){
                e.printStackTrace();
                return R.fail("验证码不正确");
            }
            User user = loginService.findByMobile(mobile,User.USER_TYPE_FAIR);
            if (user == null) {
                Ret r=passportService.reg(mobile, Constant.DEFAULT_PASSWORD,User.USER_TYPE_FAIR);
                if (r.isOk()){
                    long id= (long) r.get("id");
                    Fair fair = new Fair();
                    fair.set(Fair.ID,id);
                    fair.save();
                    user=loginService.findByMobile(mobile,User.USER_TYPE_FAIR);
                    User ref=loginService.findByCode(code,User.USER_TYPE_FAIR);
                    if (ref==null){
                        return R.fail("邀请码不存在");
                    }
                    user.set(User.REF_ID,ref.get(User.ID));
                    user.set(User.CODE,getCode());
                    user.update();
                    Dictionary dict = dictionaryDao.readDirecotryByCode(300100);
                    String val=null;
                    if (dict==null){
                        val="5";
                    }else{
                        val = dict.get(Dictionary.NAME,5);
                    }
                    MoneyLog ml = new MoneyLog();
                    ml.set(MoneyLog.WH_ID,ref.get(User.ID));
                    ml.set(MoneyLog.OPERID,user.get(User.ID));
                    ml.set(MoneyLog.STATE, MoneyLog.STATE_ADD);
                    ml.set(MoneyLog.TYPE,MoneyLog.TYPE_RENWU);
                    ml.set(MoneyLog.MONEY,val);
                    ml.set(MoneyLog.DESCRIPTION,"邀请好友获得奖励");
                    ml.save();
                }else{
                    return R.fail("注册失败");
                }
            }else{
                return R.fail("账号已存在");
            }
            return R.ok();
        }catch (Exception e){
            throw e;
        }
    }


    /**
     * 生成邀请码
     * @return
     */
    private String getCode(){
        return generateShortUuid();
    }

    private  String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z" };


    private  String generateShortUuid() {
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x3E]);
        }
        return shortBuffer.toString();
    }
}
